<template>
  <div>
    <a-card class="card" :bordered="false" :style="`min-height: ${cardMinHeight}px;`">

      <!--弹窗0 新增按钮-->
      <a-modal
          destroyOnClose
          v-model='addModal'
          width='800px'
          :title="isAdd?'新增':title"
          @ok="submit"
          @cancel="handleCancel0"
          :bodyStyle="bodyStyle"
      >
        <a-spin :spinning="spinning">
          <div style="width: 100%;min-height: 140px;display: flex;flex-direction: row;padding: 10px 24px 10px 24px;justify-content: center">
            <div style="width: 100%;">
              <a-form-model :model='addForm'   layout="inline" ref="basicFormRef" >
                <a-form-model-item
                    required
                    label="编码"
                    prop="code"
                    style="margin-left: 30px">
                  <a-input style='width: 250px;height: 32px;' v-model.trim="addForm.code" :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="规格型号"
                    prop="specificationsAndModels"
                    style="margin-left: 12px">
                  <a-input style='width: 250px;height: 32px;' v-model.trim="addForm.specification" :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    required
                    label="名称"
                    prop="name"
                    style="margin-left: 30px">
                  <a-input style='width: 250px;height: 32px;' v-model.trim="addForm.name" :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="图号"
                    prop="manufacturer"
                    style="margin-left: 40px">
                  <a-input style='width: 250px;height: 32px;' v-model.trim="addForm.figure_number" :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="单位"
                    prop="unit"
                    style="margin-left: 41px">
                  <a-popover trigger="click" placement="bottom" :overlayStyle="{ width: '250px' }">
                    <template slot="content">
                      <p class="aPopover" v-for="(item,index) in unitSearchList" :key="index"  @click="changeUnit(item)" >{{item.name}}</p>
                    </template>
                  <a-input style='width: 250px;height: 32px;'
                           v-model.trim="addForm.unit_name"
                           @keydown.enter="getUnitIdByNameLimit(addForm.unit_name)"
                           @change="getUnitIdByNameLimit(addForm.unit_name)"
                           :disabled="!canBeEdited || !isAdd"
                           allowClear
                           @click="getUnitIdByNameLimit(addForm.unit_name)"
                           placeholder="输入搜索并选择单位"></a-input>
                  </a-popover>
                </a-form-model-item>
                <a-form-model-item
                    label="安全库存"
                    prop="dateOfArrival"
                    style="margin-left: 12px">
                  <a-input style='width: 250px;height: 32px;' v-model.trim="addForm.safety_inventory" :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
              </a-form-model>

            </div>
          </div>
          <!--标签页-->
          <div style="width: 100%;min-height: 250px;display: flex;flex-direction: row;padding: 10px 24px 0px 24px;border-top: 1px solid #ddd;">
            <a-tabs type="card" :activeKey="tabKey" @change="callback" :tabBarGutter="tabBarGutter" :tabBarStyle="tabBarStyle" style="width: 100%;">
              <a-tab-pane key="1" tab="所属设备" :force-render="true">
                <div style="width: 100%;display: flex;flex-direction: row;">
                  <div style="width: 100%;">
                    <div style="display: flex;justify-content: space-between;margin-bottom: 10px;">
                      <a-popover trigger="click" placement="bottom" :overlayStyle="{ width: '160px' }">
                        <template slot="content">
                          <p class="aPopover" v-for="(item,index) in deviceSearchList" :key="index"  @click="changeDevice(item)" >{{'code:'+item.code+',name:'+item.name}}</p>
                        </template>
                          <a-input style='width: 160px;height: 32px;
                          margin-right: 10px' placeholder="*编码"
                                   v-model.trim="owningDeviceForm.code"
                                   @keydown.enter="getDeviceIdByCodeLimit(owningDeviceForm.code)"
                                   @change="getDeviceIdByCodeLimit(owningDeviceForm.code)"
                                   @click="getDeviceIdByCodeLimit(owningDeviceForm.code)"
                                   allowClear
                                   :disabled="!canBeEdited || !isAdd"></a-input>
                      </a-popover>

                      <a-popover trigger="click" placement="bottom" :overlayStyle="{ width: '160px' }">
                        <template slot="content">
                          <p class="aPopover" v-for="(item,index) in deviceSearchList" :key="index"  @click="changeDevice(item)" >{{'code:'+item.code+',name:'+item.name}}</p>
                        </template>
                      <a-input style='width: 160px;height: 32px;margin-right: 10px'
                               placeholder="*名称"
                               allowClear
                               v-model.trim="owningDeviceForm.name"
                               @keydown.enter="getDeviceIdByNameLimit(owningDeviceForm.name)"
                               @change="getDeviceIdByNameLimit(owningDeviceForm.name)"
                               :disabled="!canBeEdited || !isAdd"></a-input>
                      </a-popover>

                      <a-input style='width: 160px;height: 32px;' placeholder="规格" v-model.trim="owningDeviceForm.specification" disabled></a-input>
                      <div style="width: 247px;display: flex;  justify-content:right">
                        <a-button type="primary" style="margin-right: 15px" @click="clearAddMessage" :disabled="!canBeEdited || !isAdd">重置</a-button>
                        <a-button type="primary" @click="addDevice" :disabled="!canBeEdited || !isAdd|| !this.owningDeviceForm.code || !this.owningDeviceForm.name">添加</a-button>
                      </div>

                    </div>
                    <a-table
                        :columns="key1Columns"
                        :data-source="addForm.owningDevice"
                        :pagination="key1Pagination"
                        @change="onChangeKey1"
                        :showPagination="true"
                        :loading="tableLoading01"
                        :rowKey="(record1) => {return record1.index}"
                        :scroll="{x:true,y: 165 }"
                    >
                      <template slot="action" slot-scope="record1">
                        <a-popconfirm title="确定删除?" @confirm="() => delExtend(record1)">
                          <a>删除</a>
                        </a-popconfirm>
                      </template>
                    </a-table>
                  </div>
                </div>
              </a-tab-pane>
            </a-tabs>
          </div>
        </a-spin>

      </a-modal>


      <!--弹窗1详情-->
      <a-modal
          destroyOnClose
          class="detailModal"
          v-model='detailModal'
          width='800px'
          :title="canBeQuery?'详情':title"
          @ok="submitDetail"
          @cancel="handleCancel1"
          :bodyStyle="bodyStyle"
      >
        <a-spin :spinning="spinning">
          <div style="width: 100%;min-height: 180px;display: flex;flex-direction: row;padding: 10px 24px 10px 24px;justify-content: center">
            <div style="width: 85%;">
              <a-form-model   layout="inline" ref="basicFormRef" >
                <a-form-model-item
                    required
                    label="编码"
                    prop="code"
                    style="margin-left: 30px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="this.record.code" :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="规格型号"
                    prop="specificationsAndModels"
                    style="margin-left: 12px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="this.record.specification" :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    required
                    label="名称"
                    prop="name"
                    style="margin-left: 30px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="this.record.name" :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="图号"
                    prop="manufacturer"
                    style="margin-left: 40px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="this.record.figure_number" :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="单位"
                    prop="factoryNumber"
                    style="margin-left: 41px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="this.record.unit_name" :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="安全库存"
                    prop="dateOfArrival"
                    style="margin-left: 12px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="this.record.safety_inventory" :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="当前库存"
                    prop="acceptanceDate"
                    style="margin-left: 13px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="this.record.now_inventory" :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>

              </a-form-model>


            </div>
          </div>
          <!--标签页-->
          <div style="width: 100%;min-height: 250px;display: flex;flex-direction: row;padding: 10px 24px 0px 24px;border-top: 1px solid #ddd;">
            <a-tabs type="card" :activeKey="tabKey" @change="callback" :tabBarGutter="tabBarGutter" :tabBarStyle="tabBarStyle" style="width: 100%;">
              <a-tab-pane key="1" tab="所属设备" :force-render="true">
                <div style="width: 100%;display: flex;flex-direction: row;">
                  <div style="width: 100%;">
                    <a-table
                        :columns="detail1Columns"
                        :data-source="detail1Data"
                        :pagination="detail1Pagination"
                        @change="onChangeDetail1"
                        :showPagination="true"
                        :loading="tableLoadingDetail1"
                        :rowKey="(record1) => {return record1.index}"
                        :scroll="{x:true,y: 165 }"
                    >
                      <template slot="action" slot-scope="record">
                        <a-popconfirm title="删除?" @confirm="deleteOneFalse(record)">
                          <a>删除</a>
                        </a-popconfirm>
                      </template>
                    </a-table>
                  </div>
                </div>
              </a-tab-pane>
              <a-tab-pane key="2" tab="库存明细" :force-render="true">
                <div style="width: 100%;display: flex;flex-direction: row;">
                  <div style="width: 100%;">
                    <a-table
                        :columns="detail2Columns"
                        :data-source="detail2Data"
                        :pagination="detail2Pagination"
                        @change="onChangeDetail2"
                        :showPagination="true"
                        :loading="tableLoadingDetail2"
                        :rowKey="(recordMain) => {return recordMain.id}"
                        :scroll="{x:true,y: 165 }"
                    >
                    </a-table>
                  </div>
                </div>
              </a-tab-pane>
            </a-tabs>
          </div>
        </a-spin>
      </a-modal>

      <page-head-area>
        <div class="extra" style="width: 200px;display: flex;justify-content: space-around">
          <a-button icon="plus-circle" v-auth="`insert`" @click="add" style="background-color: #fff;border: none;margin-left: 10px;width: 70px;height: 35px;">新增</a-button>

          <a-popconfirm title="批量删除?" @confirm="deleteSelect">
            <a-button icon="delete" v-auth="`delete`" style="background-color: #fff;border: none;margin-left: 10px;width: 70px;height: 35px;">删除</a-button>
          </a-popconfirm>
<!--          <a-button icon="audit"  style="background-color: #eeeeee;border: none;margin-left: 10px;width: 70px;height: 35px;">审核</a-button>-->
        </div>
      </page-head-area>

      <div class="queryBox">
        <a-form-model layout="inline" :model='queryForm' ref="queryFormRef" class='query' style='display: flex;flex-wrap: wrap;'>
          <a-form-model-item
              label="编码"
          >
            <a-input style='width: 200px;height: 32px' v-model='queryForm.code' v-auth="`query`"></a-input>
          </a-form-model-item>
          <a-form-model-item
              label="名称"
          >
            <a-input style='width: 200px;height: 32px' v-model='queryForm.name' v-auth="`query`"></a-input>
          </a-form-model-item>

          <a-form-model-item
              label="规格"
          >
            <a-input style='width: 200px;height: 32px' v-model='queryForm.specification' v-auth="`query`"></a-input>
          </a-form-model-item>

          <a-form-model-item>
            <a-button type='primary' style='height: 32px;width: 70px;text-align: center' @click="reset" v-auth="`query`">
              重置
            </a-button>
          </a-form-model-item>

          <a-form-model-item>
            <a-button type='primary' style='height: 32px;width: 70px;text-align: center' @click="filter" v-auth="`query`">
              搜索
            </a-button>
          </a-form-model-item>
        </a-form-model>
      </div>
      <div class="dataBox">
        <a-table
            :columns="columns"
            :data-source="data"
            :pagination="false"
            :loading="tableLoading"
            :rowKey="(recordMain) => {return recordMain.id}"
            :scroll="{ x: 1000, y: 500 }"
            :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        >
          <template slot="action" slot-scope="record">
            <a v-auth="`query`" @click="detail(record)">详情</a>
            <a-divider type="vertical"/>
            <a v-auth="`update`">修改</a>
            <a-divider type="vertical"/>
            <a v-auth="`update`">申请</a>
          </template>
        </a-table>

      </div>
      <a-pagination
          @change="onChangePage"
          @showSizeChange="showSizeChange"
          :total="pagination.total"
          :showSizeChanger="true"
          :showQuickJumper="true"
          :defaultPageSize="pagination.defaultPageSize"
          :pageSize="pagination.page_size"
          :pageSizeOptions="pagination.pageSizeOptions"
          :current="pagination.current"
          :showTotal="pagination.showTotal"
          style="width: 100%;display: flex;flex-direction: row;justify-content: flex-end;margin-top: 15px"
      ></a-pagination>
    </a-card>
  </div>
</template>

<script>

import {mapGetters} from "vuex";
import PageHeadArea from "../module/pageHeadArea.vue";
import pagination from "ant-design-vue/lib/pagination";
import storage from "store";
import {DEPT_ID, ORGANIZATION_ID, USER_TOKEN} from "@/store/mutation-types";
import axios from "axios";
import moment from "moment";
import {
  file_import, file_upload,
  get_employee_list,
  get_extended_define, get_asset_file_list, get_supplier, get_unit_list, download_file,
  get_organization_list,
  delete_asset, get_asset_list, save_asset, update_asset,
  get_category_type_list, get_organization_profile_list, get_template_list, update_extend
} from "@/services/manage";
import { get_spare_parts_list} from "../../services/deviceManagement";
import {
  deleteDeviceInspection, deleteDevicePartsRelation, deleteSpareParts,
  getCacheById, getDeviceGroupList,
  getDeviceList, getDevicePartsRelationList,
  getPartsById, getSparePartsInventoryList, getSupplierById, getSupplierIdByName, getUnitIdByName,
  getUserNameById,
  listDeviceInspectionAll,
  listDeviceInspectionPlan, saveDevicePartsRelation, saveSpareParts
} from "../../utils/interface";
import {unionBy} from "lodash";
import {message} from "ant-design-vue";
const data = []
const columns = [
  { title: '编码', width: 120, align:'center',dataIndex: 'code', key: 'code'},
  { title: '名称', width: 120, align:'center',dataIndex: 'name', key: 'name'},
  { title: '规格型号', width: 120, align:'center',dataIndex: 'specification', key: 'specification'},
  { title: '图号', width: 120, align:'center',dataIndex: 'figure_number', key: 'figure_number'},
  { title: '单位', width: 120, align:'center',dataIndex: 'unit_name', key: 'unit_name'},
  { title: '安全库存', width: 120, align:'center',dataIndex: 'safety_inventory', key: 'safety_inventory'},
  { title: '当前库存', width: 120, align:'center',dataIndex: 'now_inventory', key: 'now_inventory'},
  {
    title: '操作',
    align:'center',
    key: 'operation',
    fixed: 'right',
    width: 180,
    scopedSlots: { customRender: 'action' }
  }
]

const key1Columns = [
  { title: '编码', width: 120, align:'center',dataIndex: 'id', key: 'id'},
  { title: '名称', width: 120, align:'center',dataIndex: 'name', key: 'name'},
  { title: '规格', width: 120, align:'center',dataIndex: 'specification', key: 'specification'},
  {
    title: '操作',
    align:'center',
    key: 'operation',
    fixed: 'right',
    width: 120,
    scopedSlots: { customRender: 'action' }
  }]



const detail1Columns = [
  { title: '编码', width: 120, align:'center',dataIndex: 'device_code', key: 'device_code'},
  { title: '名称', width: 120, align:'center',dataIndex: 'device_name', key: 'device_name'},
  { title: '规格', width: 120, align:'center',dataIndex: 'device_specification', key: 'device_specification'},
  {
    title: '操作',
    align:'center',
    key: 'operation',
    fixed: 'right',
    width: 180,
    scopedSlots: { customRender: 'action' }
  }
]

const detail2Columns =[
  { title: '批次', width: 120, align:'center',dataIndex: 'batch_code', key: 'batch_code'},
  { title: '库位', width: 120, align:'center',dataIndex: 'warehouse', key: 'warehouse'},
  { title: '数量', width: 120, align:'center',dataIndex: 'quantity', key: 'quantity'},
  { title: '单位', width: 120, align:'center',dataIndex: 'unit_name', key: 'unit_name'},
  { title: '价格', width: 120, align:'center',dataIndex: 'unit_price', key: 'unit_price'},
  { title: '金额', width: 120, align:'center',dataIndex: 'amount', key: 'amount'},
  { title: '供应商', width: 120, align:'center',dataIndex: 'supplier_name', key: 'supplier_name'}
]

const key1Data =[];


const detail1Data = [];

const detail2Data=[];

export default {
  name: "userAuthority",
  components: {PageHeadArea},
  data() {
    return {
      delFalseList:[],
      selectedRowKeys:[],
      record:{},
      deviceSearchList:[],
      unitSearchList:[],
      addForm:{
        'code': undefined,
        'name': undefined,
        'unit_id':undefined,
        'unit_name':undefined,
        'specification':undefined,
        'figure_number':undefined,
        'safety_inventory':undefined,
        owningDevice:[]
      },
      owningDeviceForm:{
        id:undefined,
        code:undefined,
        name:undefined,
        specification:undefined
      },
      key1Data,
      key1Columns,
      detail1Columns,
      detail1Data,
      detail2Columns,
      detail2Data,
      tableLoading01: false,

      tableLoadingDetail1:false,
      tableLoadingDetail2:false,
      axiosSource: null,
      tabKey: '1',
      title:'',
      tabBarGutter: 0,
      tabBarStyle: {
        color: 'rgba(0, 0, 0, 0.85)'
      },
      bodyStyle: {
        'padding': '0px 24px 0px 24px',
        'font-size': '14px',
        'line-height': '1.5',
        'word-wrap': 'break-word',
      },
      cardMinHeight: 0,
      queryForm: {
        code: undefined,
        name: undefined,
        specification:undefined,
      },
      data,
      columns,
      pagination: {
        total: 0,
        page_size: 10,
        defaultPageSize: 10,
        page: 1,
        current: 1,
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: total => `共 ${total} 条记录`,
        pageSizeOptions: ['10', '20', '50', '100', '500'],
      },
      tableLoading: false,
      addModal: false,
      canBeEdited: false, //是否可编辑
      isAdd: false, //是否为新增
      spinning: false,

      detailModal:false, //详情弹窗
      canBeQuery:false, //是否可查询

      key1Pagination: {
        total: 0,
        page_size: 4,
        defaultPageSize: 4,
        page: 1,
        current: 1,
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: total => `共 ${total} 条记录`,
        pageSizeOptions: ['4', '8', '10', '20', '50'],
      },
      detail1Pagination: {
        total: 0,
        page_size: 4,
        defaultPageSize: 4,
        page: 1,
        current: 1,
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: total => `共 ${total} 条记录`,
        pageSizeOptions: ['4', '8', '10', '20', '50'],
      },
      detail2Pagination: {
        total: 0,
        page_size: 4,
        defaultPageSize: 4,
        page: 1,
        current: 1,
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: total => `共 ${total} 条记录`,
        pageSizeOptions: ['4', '8', '10', '20', '50'],
      },
    }
  },
  watch: {},
  authorize: {
    add: 'insert',
    getAssetLedgerList: 'query',
    reset: 'query',
    query: 'query',
    detail: 'query',
    edit: 'update',
    del: 'delete',
    check: 'check',
  },
  computed: {
    ...mapGetters(['getCardMinHeight']),
  },
  created() {
    this.cardMinHeight = this.getCardMinHeight
  },
  async mounted() {
    this.axiosSource = axios.CancelToken.source();

    await this.initialize()
  },
  methods: {
    deleteOneFalse(record) {
      //查重
      if (!this.delFalseList.includes(record)) {
        this.delFalseList.push(record);
      }
      //逻辑删
      this.detail1Data = this.detail1Data.filter(item => item !== record)
    },
    async deleteOne(record) {
      await deleteDevicePartsRelation({'id': record.id})
    },
    async deleteSelect() {
      for (const item of this.selectedRowKeys) {
        await deleteSpareParts({'id': item})
      }
      this.selectedRowKeys = []
      message.success('删除成功')
      await this.initialize()
    },
    onSelectChange(selectedRowKeys){
      // console.log('selectedRowKeys changed: ', selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys
    },
    addDevice(){
      //查重
      const existingDevice = this.addForm.owningDevice.find(device =>
          device.id === this.owningDeviceForm.id &&
          device.code === this.owningDeviceForm.code &&
          device.name === this.owningDeviceForm.name &&
          device.specification === this.owningDeviceForm.specification
      );

      if (existingDevice) {
        // 如果设备已存在，则不添加，并给出提示
        message.error('设备已存在,请勿重复添加!');
      }
      else
      {
        this.addForm.owningDevice.push({
          'id': this.owningDeviceForm.id,
          'code': this.owningDeviceForm.code,
          'name': this.owningDeviceForm.name,
          'specification': this.owningDeviceForm.specification
        })
        this.clearAddMessage()
      }

    },
    clearAddMessage(){
      this.owningDeviceForm={
        id:undefined,
        code:undefined,
        name:undefined,
        specification:undefined
      }
      this.deviceSearchList=[]
    },
    async getUnitIdByNameLimit(unit_name) {
      await getUnitIdByName(unit_name).then(res => {
        //添加res中值到supplierSearchList
        this.unitSearchList = []
        res.slice(0, 10).forEach(item => {
          this.unitSearchList.push({
            id: item.id,
            name: item.name
          })
        })
      })
    },
    delExtend(record1){
      this.tableLoading01 =true
      this.addForm.owningDevice = this.addForm.owningDevice.filter(item => item !== record1);
      this.tableLoading01 =false
    },
    async getDeviceIdByCodeLimit(code) {
      await getDeviceList({'code': code}).then(res => {
        //添加res中值到supplierSearchList
        this.deviceSearchList = []
        res.slice(0, 10).forEach(item => {
          this.deviceSearchList.push({
            id: item.id,
            code:item.code,
            name: item.name,
            specification: item.specification
          })
        })
      })
    },
    async getDeviceIdByNameLimit(name) {
      await getDeviceList({'name': name}).then(res => {
        //添加res中值到supplierSearchList
        this.deviceSearchList = []
        res.slice(0, 10).forEach(item => {
          this.deviceSearchList.push({
            id: item.id,
            code:item.code,
            name: item.name,
            specification: item.specification
          })
        })
      })
    },
    changeUnit(item){
      console.log(item)
      this.addForm.unit_id=item.id
      this.addForm.unit_name=item.name
      this.unitSearchList=[]
    },
    changeDevice(item){
      // console.log(item)
      this.owningDeviceForm.id = item.id
      this.owningDeviceForm.code = item.code
      this.owningDeviceForm.name = item.name
      this.owningDeviceForm.specification= item.specification
      this.deviceSearchList=[]
    },
    onChangePage (page, pageSize) {
      this.pagination.current = page
      this.pagination.page_size = pageSize
      this.pagination.page = page
      this.initialize()
    },
    showSizeChange(current, size){
      this.pagination.page_size = size
      this.pagination.current = current
      this.pagination.page = current
      this.initialize()
    },
    async filter() {
      //筛选
      this.pagination.page = 1
      this.pagination.current = 1
      this.pagination.page_size = 10
      this.tableLoading = true
      console.log(this.queryForm)

      await this.initialize({
        'code':this.queryForm.code,
        'name':this.queryForm.name,
        'specification':this.queryForm.specification,
      })
      this.tableLoading = false;
    },
    async initialize(params) {
      this.tableLoading = true
      this.data = []
      const paramsAll = Object.assign({}, params, {
        "page": this.pagination.page,
        "page_size": this.pagination.page_size
      });
      await get_spare_parts_list(paramsAll).then(async res => {
        console.log(res)
        if (res.data.code === '1000') {
          this.pagination.total = res.data.extension.total+(this.pagination.current-1)*this.pagination.page_size
          for (const item of res.data.data) {
            let searchUnit = await getCacheById(item.unit_id)
            item['unit_name'] = searchUnit?.name || ''
          }
        }
        this.data = res.data.data
        this.tableLoading = false
      })
      // console.log(this.data)

    },
    // 分页切换
    onChange (pagination) {
      this.pagination.current = pagination.current
      this.pagination.page_size = pagination.pageSize
      this.pagination.page = pagination.current
      this.getAssetLedgerList()
    },
    // 分页切换
    onChangeKey1 (pagination) {
      this.key1Pagination.current = pagination.current
      this.key1Pagination.page_size = pagination.pageSize
      this.key1Pagination.page = pagination.current
    },
    onChangeDetail1(pagination) {
      this.detail1Pagination.current = pagination.current
      this.detail1Pagination.page_size = pagination.pageSize
      this.detail1Pagination.page = pagination.current
    },
    onChangeDetail2(pagination) {
      this.detail2Pagination.current = pagination.current
      this.detail2Pagination.page_size = pagination.pageSize
      this.detail2Pagination.page = pagination.current
    },
    async query() {
      this.pagination.page = 1
      this.pagination.current = 0
      this.pagination.page_size = 10
      this.tableLoading = true
      await this.initialize()
      this.tableLoading = false
    },
    callback (key) { // assetCode
      this.tabKey = key
    },
    reset() {
      this.queryForm = {
        code: undefined,
        name: undefined,
        specification:undefined,

      }
      this.query()
    },
    add() {
      this.addModal = true
      this.canBeEdited = true
      this.isAdd = true
      this.spinning = false
    },
    edit(record) {
      this.addModal = true
      this.canBeEdited = true
      this.isAdd = false
      this.echo(record)
    },
    async submitDetail() {
      if (this.delFalseList.length > 0) {
        for (const delItem of this.delFalseList) {
          await this.deleteOne(delItem); // 等待每个删除操作完成
        }
        message.success('删除成功')
      }
      this.detailModal = false
      this.canBeQuery = false
    },
    async detail(record) {
      // console.log(record)
      this.delFalseList=[]
      this.record = record
      this.detailModal = true
      this.canBeEdited = false
      this.canBeQuery = true
      this.isAdd = false
      this.detail1Data=[]
      this.detail2Data=[]
      this.tableLoadingDetail1=true
      this.tableLoadingDetail2=true
      this.tabKey="1"
      //获得相关设备
      await getDevicePartsRelationList({'parts_id':record.id}).then(async res => {
        if (res.length !==0) {
          for (const it of res) {
            console.log(it)
            let searchDevice = await getDeviceList({'id': it.device_id})
            it['device_name'] = searchDevice[0]?.name || ''
            it['device_code'] = searchDevice[0]?.code || ''
            it['device_specification'] = searchDevice[0]?.specification || ''

          }
        }
        this.detail1Data=res
        this.tableLoadingDetail1 = false
      })
      this.tableLoadingDetail1=false
      //获得相关库存
      await getSparePartsInventoryList({'spare_parts_id':record.id}).then(async res => {
        if (res.length !==0) {
          for (const it2 of res) {
            it2['supplier_name'] = await getSupplierById(it2.supplier_id)[0]?.name || ''
            let searchUnit = await getCacheById(it2.unit_id)
            it2['unit_name'] = searchUnit?.name || ''
          }
          this.detail2Data =res
          this.tableLoadingDetail2 = false
          console.log(this.detail2Data)
        }

      })

      this.tableLoadingDetail2=false
    },
    clearParameter() {
      this.addForm={
        'code': undefined,
        'name': undefined,
        'unit_id':undefined,
        'unit_name':undefined,
        'specification':undefined,
        'figure_number':undefined,
        'safety_inventory':undefined,
        owningDevice:[]
      }
      this.deviceSearchList=[]
      this.unitSearchList=[]
    },
    handleCancel0() {
      this.addModal = false
      this.canBeEdited = false
      this.isAdd = false
    },
    handleCancel1(){
      this.delFalseList=[]
      this.detailModal = false
      this.canBeEdited = false
      this.canBeQuery =false
      this.isAdd = false
    },
    handleCancel2(){
      this.disposalModal = false
      this.canBeEdited = false
      this.canBeQuery =false
      this.isAdd = false
    },
    async submit() {
      //
      if (this.addForm.code === undefined
          || this.addForm.name === undefined
      ) {
        message.error('请填写完整信息')
        return
      }
        //查重code
        let searchList = await getPartsById({'code': this.addForm.code})
        let flag = true
        if (searchList.length > 0) {
          for (let i = 0; i < searchList.length; i++) {
            if (searchList[i].code === this.addForm.code) {
              flag = false
              break;
            }
          }
        }
        if (flag === false) {
          message.error("备品备件编码重复！")
          return
        }

        // message.info("正在提交")
        //传配件
        await saveSpareParts({
          'code': this.addForm.code,
          'name': this.addForm.name,
          'safety_inventory': this.addForm.safety_inventory,
          'specification': this.addForm.specification,
          'figure_number': this.addForm.figure_number,
          'unit_id':this.addForm.unit_name===undefined?null:this.addForm.unit_id,

        })
        //拿id
        console.log(this.addForm)
        if(this.addForm.owningDevice.length !== 0){
          let searchPart = await getPartsById({'code': this.addForm.code})
          let searchPartOne = searchPart.find(InIt=>InIt.code===this.addForm.code)
          if(searchPart.length>0){
            for (const deviceIt of this.addForm.owningDevice) {
              await saveDevicePartsRelation({
                'device_id': deviceIt.id,
                'parts_id': searchPartOne.id
              })
            }
          }

        }

        message.success("新增成功")
        this.handleCancel0()
        this.clearParameter()
        await this.initialize()

    },
  },
  beforeDestroy() {
    if (this.axiosSource) {
      this.axiosSource.cancel('Request canceled due to page navigation.');
    }
  }
}
</script>

<style scoped lang="less">

.aPopover{
}
.aPopover:hover {
  background-color: #EA5413;
}
.dataBox{
  margin-top: 20px;
}

.hide-scrollbar::-webkit-scrollbar {
  display: none; /* 隐藏滚动条 */
}

::-webkit-scrollbar {
  display: none; /* 隐藏滚动条 */
}
.hide-scrollbar {
  -ms-overflow-style: none;  /* IE 和 Edge */
  scrollbar-width: none;  /* Firefox */
  overflow-y: scroll; /* 保持内容可滚动 */
}
.demo-infinite-container {
  margin-top: 0px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  overflow: auto;
  padding: 8px 24px;
  height: 300px;
}
/deep/ .ant-form-inline .ant-form-item-with-help{
  margin-bottom: 0px;
}
/deep/ .ant-input[disabled]{
  pointer-events: none;
  color: #000000d9;
  background-color: #f5f5f5;
  cursor: not-allowed;
  opacity: 1;
}
/deep/ .unit .ant-select-selection--single{
  margin-left: 0px;
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
  border-left: 0;
}
/deep/ .ant-select-disabled .ant-select-selection {
  background-color: #fff;
}
/deep/ .ant-input[disabled]{
  pointer-events: none;
  color: #000000d9;
  background-color: #fff;
  cursor: not-allowed;
  opacity: 1;
}
/deep/ .ant-input-number-disabled{
  pointer-events: none;
  color: #000000d9;
  background-color: #fff;
  cursor: not-allowed;
  opacity: 1;
}
</style>